<?php
/**
 * command.php -- send commands to Xine
 */

require_once("config.php");

?>
<html>
 <head><title>xine-remote command test</title></head>
 <body>
 <pre>
<?php 
//var_export($_REQUEST); 
//print("\n");
$cnum = 0;
if (count($_REQUEST) == 0) {
	print("Ready for commands\n");
} else foreach ($_REQUEST as $cmdstring => $unused) {
	$cmds = split(";",$cmdstring);
	foreach ($cmds as $cmdstr) {
		$parts = split(",", $cmdstr);
		$cmd = $parts[0];
		$params = array_slice($parts, 1);
		if (count($parts) > 1) {
			$pstr = join(", ", $params);
		} else {
			$pstr = "no params";
		}
		printf("[%02d] %s (%s)\n", ++$cnum, $cmd, $pstr);
		run_task($cmd, $params);
	}
}
//print("Playlist:\n");
//run_task("playlist");
?>
 </pre>
 </body>
</html>

<?php 

function run_task($cmd, $params="") {
	switch ($cmd) {
	case "pause":
	case "play":
	case "stop":
		xine_cmd($cmd);
		break;
	case "prev":
	case "next":
		xine_cmd("playlist $cmd");
		break;
	case "playlist":
		xine_cmd("playlist show");
		break;
	case "seek":
		$delta = $params[0];
		if ($delta > 0) {
			$delta = sprintf("+%d", $delta);
		}
		xine_cmd("seek ".$delta);
		break;
	case "volume":
		$delta = $params[0];
		if ($delta > 0) {
                        $delta = sprintf("+%d", $delta);
                }
		vol_adjust($delta);
		break;
	case "jiggle":
		global $XSCR, $XAUTH, $DISPLAY;
		print("sudo DISPLAY=$DISPLAY XAUTHORITY=$XAUTH $XSCR -deactivate\n");
		run_cmd("sudo DISPLAY=$DISPLAY XAUTHORITY=$XAUTH $XSCR -deactivate");
		print("Done jiggling\n");
		break;
	default:
		printf("Command not handled: %s (%s)\n", $cmd, join(", ", $params));
	}
}

function xine_cmd($cmd) {
	global $XINE;
	run_cmd("$XINE -c '$cmd'");
}

function vol_adjust($delta) {
	global $AUMIX;
	run_cmd("$AUMIX -w$delta -w q");
}

function run_cmd($cmd, $print=false) {
	$rint = null;
	$rstr = system($cmd, &$rint);
	if ($print) printf("%s\nReturned value %d:\n%s\n\n", $cmd, $rint, $rstr);
}
